package com.sky.aspect;

import com.sky.anno.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import javassist.bytecode.SignatureAttribute;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    //切点表达式
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anno.AutoFill)")
    public void pointcut(){};

    //前置通知
    @Before("pointcut()")
    public void beforeAspect(JoinPoint joinPoint){
        log.info("开始自动填充公共字段");
       //获取签名方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法上的注解的value
        OperationType value = signature.getMethod().getAnnotation(AutoFill.class).value();
        //获取实体对象
        Object[] args = joinPoint.getArgs();
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //获取当前操作者的id
        Long currentId = BaseContext.getCurrentId();
        if(args.length==0){
            return;
        }
        Object entity=args[0];
        if(OperationType.INSERT==value){
            //当前操作为插入操作
            try {
                Method create_time = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method update_time = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method create_user = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method update_user = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                //通过反射为属性赋值
                create_time.invoke(entity,now);
                update_time.invoke(entity,now);
                create_user.invoke(entity,currentId);
                update_user.invoke(entity,currentId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        } else if (OperationType.UPDATE==value) {
            //当前操作为更新操作
            try {
                Method update_time = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method update_user = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                //通过反射为属性赋值
                update_time.invoke(entity,now);
                update_user.invoke(entity,currentId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
